/*
 * This is adapter of spinner for data object that derived from NamedObject 
 * */
package nautilus.moneykeeper.adapter;

import java.util.ArrayList;

import nautilus.moneykeeper.R;
import nautilus.moneykeeper.dto.NamedObject;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

public class SpinnerNamedAdapter<T> extends BaseAdapter implements SpinnerAdapter{
	private ArrayList<T> _objects = new ArrayList<T>();
	private Context _context;
	private LayoutInflater inflater;
	
	public SpinnerNamedAdapter(Context context, ArrayList<T> lstCat) {		
		_context = context;
		_objects.addAll(lstCat);
		inflater = ((Activity)_context).getLayoutInflater();
	}
	
	public void refreshData(ArrayList<T> list){
		_objects.clear();
		_objects.addAll(list);
		notifyDataSetChanged();
	}
	
	public void addMoreData(ArrayList<T> list){
		_objects.addAll(list);
		notifyDataSetChanged();
	}
	
	public void addItem(T item){
		_objects.add(item);
		notifyDataSetChanged();
	}
	
	@Override
	public int getCount(){
		return _objects.size();
	}
	
	@Override
	public Object getItem(int pos){
		return _objects.get(pos);
	}
	
	@Override 
	public long getItemId(int pos){
		return ((NamedObject)_objects.get(pos)).getId();
	}
	
	@Override
	public View getView(int pos, View convertView, ViewGroup viewGroup){
		return getCustomView(pos, convertView, viewGroup);
	}
	
	private View getCustomView(int pos, View convertView, ViewGroup viewGroup){
		
		View rowView = convertView;
		TextView tView;
		if(rowView == null){
			rowView = inflater.inflate(R.layout.simple_list_item, viewGroup, false);
			tView = (TextView)rowView.findViewById(R.id.simple_list_item);
			rowView.setTag(tView);
			
		}else{
			tView = (TextView)rowView.getTag();
		}
		
		T obj = _objects.get(pos);
		tView.setText( ((NamedObject)obj).getName());
		/*
		View rowView = convertView;
		TextView tView;
		Log.i(TAG, "view resource id: " + _textViewResourceId);
		//get an instance of row layout
		LayoutInflater inflater = ((Activity)_context).getLayoutInflater();
		rowView = inflater.inflate(_textViewResourceId, viewGroup, false);	
		tView = (TextView)rowView.findViewById(R.id.spinner_item_spinner);
		Category obj = _objects.get(pos);
		tView.setText(obj.getName());
		*/
		
		return rowView;
	}
}
